package com.helloandroid.models.butie

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.app.model.AppCache
import com.helloandroid.ext.parseHeShuiInfo
import com.helloandroid.ext.process
import com.helloandroid.tools.Http.asyncHttpReq
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.NetWorkUtil
import com.helloandroid.vo.HeShuiInfo
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

class HeShuiViewModel : ViewModel() {

    fun getInfo(callback:(Boolean,heShuiInfo:HeShuiInfo?)->Unit){

        val info = AppCache.copyHeShuiInfo()
        if (info != null){
            callback(true,info)
            return
        }

        if (!NetWorkUtil.networkConnected()){
            AppUtil.toast("请打卡网络!")
            callback(false,null)
            return
        }

        viewModelScope.launch {
            val url = "butie/heshui/info?user_id=${AppUtil.user.user_id}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseHeShuiInfo)
            if (parseResult.err == 0){
                val hsInfo = parseResult.obj as HeShuiInfo
                AppCache.heShuiInfo = hsInfo
                callback(true,AppCache.copyHeShuiInfo())
            }else{
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
                callback(false,null)
            }
        }
    }

    fun delayExecute(ms:Long,action:()->Unit){
        viewModelScope.launch {
            delay(ms)
            action.invoke()
        }
    }
}